#
# Copyright (c) 2002-2007 Eric Wallengren
# This file is part of the Continuous Automated Build and Integration
# Environment (CABIE)
#
# CABIE is distributed under the terms of the GNU General Public
# License version 2 or any later version.  See the file COPYING for copying
# permission or http://www.gnu.org.
#
# THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED OR
# IMPLIED, without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  ANY USE IS AT YOUR OWN RISK.
#
# Permission to modify the code and to distribute modified code is granted,
# provided the above notices are retained, and a notice that the code was
# modified is included with the above copyright notice.
#

package common;

# use strict;
use Exporter;
use Carp;
use Sys::Hostname;

my $ospackage;
my $bamDarwin = 0;
my $POSIX     = 1;
my $queries;
my $config;
my $cmbroker;

my %elapsed_time;

#
# See if this is a windoz system...
#
if ($^O =~ /MSWin32/) {
    $POSIX = 0;
    $ospackage  = "winsys";
} else {
    $ospackage  = "unixsys";
    if ($^O =~ /darwin/ic) {
        $bamDarwin = 1;
    }
}

my $hostname     = hostname();
$hostname        =~ s/\.[a-zA-Z0-9]+//g;

my $configname   = $hostname;
$configname      =~ s/-//g;

#
# Load master configuration file
#
require "$configname.pm";

#
# Create instances of packages enabled above...
#
my $config = new $configname;

use queries;

my $queries = new queries;

#
# unixsys for posix
# winsys for windows
#
require "$ospackage.pm";

#
# Create instances of packages enabled above...
# unixsys for posix
# winsys for windows
#
my $os  = new $ospackage;

use cmbroker;
$cmbroker = new cmbroker;

@ISA     = qw/ Exporter AutoLoader /;
@EXPORT  = qw/ _gen_time_string _copycontents _do_popupstring _do_popup 
               _do_popup2 _format_elapsed_time _catfile _cmd_array 
               secsToTime _ispromoted _formatuseraddress tableData 
               makeLink /;

sub _gen_time_string {

    my $arg = $_[1];
    my $returnstring;

    $os->tracefunction((caller(0))[3]);

    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
        = localtime($_[0]);

    if ($arg == 1) {
        $returnstring = sprintf("%02d/%02d/%04d\@%02d:%02d:%02d\n", $mon+1,
            $mday, 1900 + $year, $hour, $min, $sec);
    } else {
        $returnstring = sprintf("%02d/%02d/%04d %02d:%02d:%02d\n", $mon+1,
            $mday, 1900 + $year, $hour, $min, $sec);
    }

    return $returnstring;

}

sub _copycontents {

    my $in      = shift;
    my $out     = shift;
    my $search  = shift;
    my $replace = shift;

    $os->tracefunction((caller(0))[3]);

    if (-f $in) {
        open (IS, "<$in");
        open (OS, ">$out");

        while (<IS>) {
            my $newline = $_;
            $newline =~ s/$search/$replace/g;
            print OS "$newline";
        }
        close(IS);
        close(OS);
    }

    return 0;

}

#
# 3 routines to generate javascript
#
sub _do_popupstring {

    my $webserver = shift;
    my $server    = shift;
    my $title     = shift;
    my $jobno     = shift;

    $os->tracefunction((caller(0))[3]);

    return "\"javascript:loadpopup(\'$webserver\',\'$server\',\'$title\', ".
           "\'$jobno\');\"";
}

sub _do_popup {

    my $string = shift;
    my $title  = shift;
    chomp $string;
    chomp $title;

    $os->tracefunction((caller(0))[3]);

    $string =~ s/\n/\<br\>/g;

    return "onmouseout=kill(); onmouseover=\"pop(\'<font size=1>$string".
           "</font>\','#B3AFE9',\'$title\'); return false\"";

}

sub _do_popup2 {

    my $string = shift;
    my $title  = shift;
 
    my @newstring;

    $os->tracefunction((caller(0))[3]);

    chomp $title;
    # $string =~ s/\n/\<br\>/g;
    @newstring = split(/\n/, $string);
    $string = "";

    foreach my $entry (@newstring) {
        chomp $entry;
        $string .= "$entry<br>";
        $string =~ s/\r//g;
    }

    return "onmouseout=kill(); onmouseover=\"pop(\'<font size=1>$string".
           "</font>\','#B3AFE9',\'$title\'); return false\"";

}

sub _cmd_array {

    my $cmd = shift;

    $os->tracefunction((caller(0))[3]);

    open (DIRFD, "$cmd|");
    my @psarray = <DIRFD>;
    close (DIRFD);
    unshift(@psarray, "\n");
    return @psarray;

}

sub _format_elapsed_time {

    my $difference = shift;

    $os->tracefunction((caller(0))[3]);

    my $seconds    =  $difference % 60;
    my $difference = ($difference - $seconds) / 60;
    my $minutes    =  $difference % 60;
    my $difference = ($difference - $minutes) / 60;
    my $hours      =  $difference % 24;
    my $difference = ($difference - $hours)   / 24;
    my $days       =  $difference % 7;
    my $weeks      = ($difference - $days)    /  7;

    my $returnstring = sprintf("%02d:%02d:%02d", $hours, $minutes,$seconds);

    return $returnstring;

}

sub _catfile {

    my $filename = shift;
    my @contents;

    $os->tracefunction((caller(0))[3]);

    if (-f "$filename") {
        open (LF, "<$filename") || die "open: $?";
        @contents = <LF>;
        close (LF);
    } else {
        push @contents, "$filename not found";
    }

    return @contents;

}

# ------------------------------------------------------------------
sub outputTimeCell {

    my $who  = shift; 
    my $when = shift;

    $os->tracefunction((caller(0))[3]);

    my $time = secsToTime( $elapsed_time{ $who, $when } );

    if ( ! $time ) {

        $time = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";

    }

    return "    <td class='time'>$time</td>\n";

}

# ------------------------------------------------------------------
sub secsToTime {

    my $secs = shift;

    $os->tracefunction((caller(0))[3]);

    if ( $secs > 0 ) {

        my $min = 0;
        my $sec = 0;

        if ( $secs >= 60 ) {

            $min = int( $secs / 60 );
            $sec = $secs % 60;

        } else {

            $sec = $secs;

        }

        return sprintf( "%d' %02d\"", $min, $sec );

    } else {

        return "";

    }

}

sub _ispromoted {

    my $jobname = shift;
    my $jobno   = shift;

    my $sqlquery;
    my @sqlarray;

    my $recs;

    my $webroot = $config->WEBROOT;

    $os->tracefunction((caller(0))[3]);

    $sqlquery = $queries->formatquery(114, $jobname, $jobno);

    @sqlarray = $os->run_sql_query("$sqlquery", ";", 0);

    $recs = @sqlarray;

    if (!$recs) {
        return "<a href=$webroot/$hostname/$jobname/$jobno>$jobno</a>";
    }

    return "<a href=$webroot/promotion/$jobname/$jobno>$jobno</a>";

}

sub _formatuseraddress {

    my $username = shift;
    my $sccs     = shift;
    my $port     = shift;

    my $cmd;
    my $email;

    $os->tracefunction((caller(0))[3]);

    $cmd = $sccs."_useraddress";

    $email = $cmbroker->$cmd($username, $port);

    my ($add, $full) = split(/:/,$email);

    $os->writelog("$email", *STDERR);

    return "<a href=mailto:$add>$full</a>";

}

sub tableData {

    my %tabledata = @_;
    my @ret = ();

    $os->tracefunction((caller(0))[3]);

    push @ret, "<tr>\n";

    foreach my $key (sort keys %tabledata) {
    
        my $content = $tabledata{$key}{content};
        my $class   = $tabledata{$key}{class};
        my $width   = $tabledata{$key}{width};
        my $colspan = $tabledata{$key}{colspan};

        my $entry = "    <td";

        if (defined($class)) {
            $class = "class=$class";
            $entry .= " $class";
        }

        if (defined($width)) {
            $width = "width=$width";
            $entry .= " $width";
        }

        if (defined($colspan)) {
            $colspan = "colspan=$colspan";
            $entry .= " $colspan";
        }

        $entry .= ">$content</td>\n";

        $os->writelog("$entry", *STDERR); 

        push @ret, $entry;

    }

    push @ret, "</tr>\n";

    %tabledata = ();

    return @ret;

} 

sub makeLink {;

    my $link = shift;
    my $desc = shift;

    $os->tracefunction((caller(0))[3]);

    return "<a href=$link>$desc</a>";

}

1;
